import axios from 'axios'
import store from '@/store/index'
import router from '@/router/index'
import { Message } from 'element-ui'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
service.interceptors.request.use((config) => {
  const token = store.getters.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, (error) => {
  Message.error(error.message)
  return Promise.reject(error)
})

service.interceptors.response.use((response) => {
  if (response.data instanceof Blob) return response.data
  const { success, data, message } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, async(error) => {
  if (error.response.status === 401) {
    Message.error('token失效了')

    await store.dispatch('user/back')
    router.push('/login')
    return Promise.reject(error)
  }
  Message.error(error.message)
  return Promise.reject(error)
})
export default service
